package com.jie.algorithm.ui.setting;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import com.jie.algorithm.R;

/**
 * @author H.J.
 * @date 2020/6/8 16:11
 * @description 真正的设置界面
 */
public class SettingFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static SettingFragment newInstance() {
        return new SettingFragment();
    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.pref_general);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 注册SharedPreference改变监听
        SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences();
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);
        // 初始化Summary
        onSharedPreferenceChanged(sharedPreferences, getString(R.string.pref_key_count));
        onSharedPreferenceChanged(sharedPreferences, getString(R.string.pref_key_algorithm));
    }

    @Override
    public void onPause() {
        super.onPause();
        SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences();
        sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        String value = sharedPreferences.getString(key, "");
        Preference preference = findPreference(key);
        if (preference instanceof ListPreference){
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(value);
            preference.setSummary(
                    index >= 0
                            ? listPreference.getEntries()[index]
                            : getString(R.string.please_choose));
        }else{
            value = TextUtils.isEmpty(value) ? getString(R.string.please_input) : value;
            preference.setSummary(value);
        }
    }
}
